package com.sangfor.ssl.service.timeqry;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import com.sangfor.bugreport.logger.Log;
import com.sangfor.ssl.common.ReasonCode;
import com.sangfor.ssl.easyapp.SangforAuthForward;
import com.sangfor.ssl.l3vpn.service.IVpnStatusChangedListener;
import com.sangfor.ssl.l3vpn.service.L3vpnController;
import com.sangfor.ssl.l3vpn.service.LoginState;
import com.sangfor.ssl.l3vpn.service.VpnServiceManager;
import com.sangfor.ssl.l3vpn.service.VpnStatus;
import com.sangfor.ssl.service.https.SFException;
import com.sangfor.ssl.service.setting.GlobalSettingUtils;
import com.sangfor.ssl.service.setting.SettingManager;
import com.sangfor.ssl.service.setting.SystemConfiguration;
import com.sangfor.ssl.service.timeqry.TQProtocol;
import com.sangfor.ssl.service.utils.IGeneral;
import com.sangfor.ssl.service.utils.network.HttpConnect;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.util.Enumeration;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicLong;

/* loaded from: classes2.dex */
public class TimeQryService extends Service implements IVpnStatusChangedListener {
    public static final String ACTION_RESTART_TIMEQRY = "com.sangfor.action.ACTION_RESTART_TIMEQRY";
    private static final int MSG_RDB_TIME_CHANGED = 2;
    private static final int MSG_RESTART_TIMEQRY_THREAD = 1;
    public static final int MSG_TIMEQRY_SHUTDOWN = 7;
    public static final int MSG_TIMEQRY_START_FAILED = 6;
    private static final int MSG_UPDATE_LOGIN_OFFLINE = 4;
    private static final int MSG_UPDATE_LOGIN_ONLINE = 3;
    private static final long QUERY_INTERVAL_DEFAULT = 1000;
    private static final long QUERY_INTERVAL_SCREEN_OFF = 10000;
    private static final long QUERY_INTERVAL_TURBO_MODE = 4000;
    private static final int QUERY_TIMES_DEFAULT = 10;
    private static final int QUERY_TIMES_SCREEN_OFF = 3;
    private static final long RECONNECT_INTERVAL_DEFAULT = 8000;
    private static final String TAG = "TimeQryService";
    private static final long TIME_QUERY_TIME = 300000;
    private static final String URL_SESSION_CHANGE = "/por/timequery.csp?msg=logout&oldsessid=";
    private static final int VPN_DISCONNECTED_TURBO_TIMES = 5;
    private TimeQryTask mTimeQryTask;
    private int mSslPort = IGeneral.DEFAULT_SSL_PORT;
    private String mIpAddr = "";
    private final IBinder mBinder = new TimeQryBinder();
    private final AtomicLong mTimeoutTime = new AtomicLong();
    private int mInterruptedTimes = 0;
    private long mTotalTime = 0;
    private long mStartTime = 0;
    private long mTimes = 0;
    private long mErrCount = 0;
    private volatile boolean mIsLogedOut = true;
    private volatile boolean mIsUpdate = false;
    private volatile Thread mTimeQryThread = null;
    private volatile int mTurboTimes = 1;
    private final Object mLock = new Object();
    private String mPreIp = "";
    private long mQueryInterval = QUERY_INTERVAL_DEFAULT;
    private int mQueryTimes = 10;
    private MyHandler mHandler = new MyHandler(Looper.getMainLooper(), this);
    private BroadcastReceiver mTurboReceiver = new BroadcastReceiver() { // from class: com.sangfor.ssl.service.timeqry.TimeQryService.1
        @Override // android.content.BroadcastReceiver
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("android.intent.action.SCREEN_ON".equals(action)) {
                TimeQryService.this.updateQueryFrequency(TimeQryService.QUERY_INTERVAL_DEFAULT, 10);
                TimeQryService.this.setTurboMode(true);
            } else if ("android.intent.action.SCREEN_OFF".equals(action)) {
                TimeQryService.this.updateQueryFrequency(TimeQryService.QUERY_INTERVAL_SCREEN_OFF, 3);
            }
        }
    };
    private BroadcastReceiver mReStartTimeQryReceiver = new BroadcastReceiver() { // from class: com.sangfor.ssl.service.timeqry.TimeQryService.2
        @Override // android.content.BroadcastReceiver
        public void onReceive(Context context, Intent intent) {
            if (intent == null || !TimeQryService.ACTION_RESTART_TIMEQRY.equals(intent.getAction())) {
                return;
            }
            Log.info(IGeneral.LOG_TAG_TIMEQRY, "prepare restart Timeqry.");
            TimeQryService.this.stopThread();
            TimeQryService.this.mHandler.sendEmptyMessageDelayed(1, 500L);
        }
    };

    @Override // com.sangfor.ssl.l3vpn.service.IVpnStatusChangedListener
    public void onPermissionRevoke() {
    }

    @Override // android.app.Service
    public int onStartCommand(Intent intent, int i, int i2) {
        return 2;
    }

    static /* synthetic */ long access$808(TimeQryService timeQryService) {
        long j = timeQryService.mErrCount;
        timeQryService.mErrCount = 1 + j;
        return j;
    }

    /* loaded from: classes2.dex */
    public class TimeQryBinder extends Binder {
        public TimeQryBinder() {
        }

        public TimeQryService getService() {
            return TimeQryService.this;
        }
    }

    @Override // android.app.Service
    public IBinder onBind(Intent intent) {
        Log.info(IGeneral.LOG_TAG_TIMEQRY, "onBind TimeQuery service.");
        return this.mBinder;
    }

    @Override // android.app.Service
    public boolean onUnbind(Intent intent) {
        Log.info(IGeneral.LOG_TAG_TIMEQRY, "onUnbind TimeQuery service");
        return super.onUnbind(intent);
    }

    @Override // android.app.Service
    public void onRebind(Intent intent) {
        super.onRebind(intent);
        Log.info(IGeneral.LOG_TAG_TIMEQRY, "onRebind TimeQuery service");
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void updateQueryFrequency(long j, int i) {
        this.mQueryInterval = j;
        this.mQueryTimes = i;
    }

    @Override // android.app.Service
    public void onCreate() {
        super.onCreate();
        this.mIsLogedOut = false;
        Log.info(IGeneral.LOG_TAG_TIMEQRY, "onCreate TimeQuery service");
        registerTurboReceiver();
        registerVpnStatusChanged();
        registerRestartTimeQry();
    }

    @Override // android.app.Service
    public void onDestroy() {
        Log.info(IGeneral.LOG_TAG_TIMEQRY, "onDestroy TimeQuery service");
        this.mIsLogedOut = true;
        unRegisterTurboReceiver();
        unRegisterVpnStatusChanged();
        unRegisterRestartTimeQry();
        stopThread();
        super.onDestroy();
    }

    private void registerTurboReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.SCREEN_ON");
        intentFilter.addAction("android.intent.action.SCREEN_OFF");
        registerReceiver(this.mTurboReceiver, intentFilter);
    }

    private void unRegisterTurboReceiver() {
        unregisterReceiver(this.mTurboReceiver);
    }

    private void registerVpnStatusChanged() {
        VpnServiceManager.getInstance().registerListener(this);
    }

    private void unRegisterVpnStatusChanged() {
        VpnServiceManager.getInstance().unregisterListener(this);
    }

    @Override // com.sangfor.ssl.l3vpn.service.IVpnStatusChangedListener
    public void onVpnStatusChanged(VpnStatus vpnStatus, int i) {
        int i2 = AnonymousClass3.$SwitchMap$com$sangfor$ssl$l3vpn$service$VpnStatus[vpnStatus.ordinal()];
        if (i2 == 1) {
            setTurboMode(false);
        } else if (i2 != 2) {
        } else {
            setTurboTimes(5);
        }
    }

    public void setUpdatePattern(boolean z) {
        this.mIsUpdate = z;
    }

    @Override // android.app.Service
    public void onStart(Intent intent, int i) {
        super.onStart(intent, i);
        this.mIsLogedOut = false;
    }

    public synchronized void startThread() {
        SystemConfiguration.VpnInfo vpnInfo = SystemConfiguration.getInstance().getVpnInfo();
        if (vpnInfo != null && !TextUtils.isEmpty(vpnInfo.getHost())) {
            this.mIpAddr = vpnInfo.getHost();
            this.mSslPort = vpnInfo.getPort();
            Log.info(IGeneral.LOG_TAG_TIMEQRY, String.format(Locale.getDefault(), "onStart TimeQuery service,ip:%s,port:%d", this.mIpAddr, Integer.valueOf(this.mSslPort)));
            stopThread();
            Log.info(IGeneral.LOG_TAG_TIMEQRY, "TimeQuery start");
            SettingManager.getInstance().setGlobalValue(SettingManager.GLOBAL_TIMEQRY_UPDATE, 1);
            this.mErrCount = 0L;
            this.mIsLogedOut = false;
            this.mTimeQryTask = new TimeQryTask();
            this.mTimeQryThread = new Thread(this.mTimeQryTask, String.format("TimeQry [%s]", (String) SettingManager.getInstance().get(SettingManager.TWFID_TWFID)));
            this.mTimeQryThread.start();
            Log.info(IGeneral.LOG_TAG_TIMEQRY, "TimeQryThread Started :" + this.mTimeQryThread.getId() + "TimeQryThread Name:" + this.mTimeQryThread.getName());
            return;
        }
        Log.warn(IGeneral.LOG_TAG_TIMEQRY, "can out find service VpnInfo or ip address is empty, logout");
        this.mHandler.sendEmptyMessage(6);
    }

    public synchronized void stopThread() {
        if (this.mTimeQryThread != null && this.mTimeQryThread.isAlive()) {
            Log.info(IGeneral.LOG_TAG_TIMEQRY, "interrupt TimeQuery thread");
            Thread thread = this.mTimeQryThread;
            this.mTimeQryThread = null;
            if (thread != null) {
                thread.interrupt();
            }
            this.mTimeQryTask.stop();
            this.mTimeQryTask = null;
        }
    }

    public long getDuration() {
        if (this.mInterruptedTimes >= 1) {
            return this.mTotalTime;
        }
        if (this.mStartTime > 0) {
            return this.mTotalTime + (System.currentTimeMillis() - this.mStartTime);
        }
        return this.mTotalTime;
    }

    public void setTurboMode(boolean z) {
        setTurboTimes(z ? 1 : 0);
    }

    private void setTurboTimes(int i) {
        synchronized (this.mLock) {
            this.mTurboTimes = i;
            if (this.mTurboTimes > 0) {
                synchronized (this.mLock) {
                    this.mLock.notifyAll();
                }
            }
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public Socket connectToServer() {
        Socket socket;
        Log.info(IGeneral.LOG_TAG_TIMEQRY, "try to connect %s:%d", this.mIpAddr, Integer.valueOf(this.mSslPort));
        try {
            socket = new Socket();
            try {
                socket.connect(new InetSocketAddress(this.mIpAddr, this.mSslPort), IGeneral.CONN_SERVICE_TIMEOUT);
                if (handShakeWithService(socket)) {
                    this.mStartTime = System.currentTimeMillis();
                    Log.info(IGeneral.LOG_TAG_TIMEQRY, "connect vpn success, %s:%d", this.mIpAddr, Integer.valueOf(this.mSslPort));
                    return socket;
                }
            } catch (Exception e) {
                e = e;
                closeSocketQuietly(socket);
                Log.warn(IGeneral.LOG_TAG_TIMEQRY, "fail to connect [%s:%d], connect again later.", this.mIpAddr, Integer.valueOf(this.mSslPort), e);
                return null;
            }
        } catch (Exception e2) {
            e = e2;
            socket = null;
        }
        return null;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void mainWork(Socket socket) throws TimeQryException {
        ClientMessage clientMessage = new ClientMessage();
        ServerMessage serverMessage = new ServerMessage();
        Thread currentThread = Thread.currentThread();
        while (!this.mIsLogedOut && !currentThread.isInterrupted() && currentThread == this.mTimeQryThread) {
            this.mTimes++;
            SettingManager settingManager = SettingManager.getInstance();
            String twfid = GlobalSettingUtils.getTwfid();
            Integer num = (Integer) settingManager.getGlobalValue(SettingManager.GLOBAL_TIMEQRY_UPDATE);
            int i = 3;
            if (this.mIsUpdate && this.mTimes % 3 == 0) {
                i = 1;
            }
            if (num != null && num.intValue() == 0) {
                settingManager.setGlobalValue(SettingManager.GLOBAL_TIMEQRY_UPDATE, 1);
                i = 1;
            }
            if (TextUtils.isEmpty(twfid)) {
                Log.error(TAG, "TimeQryMainWork ERROR! Twfid is empty!");
                return;
            }
            try {
                send(socket, clientMessage.pack(i, (int) (System.currentTimeMillis() / QUERY_INTERVAL_DEFAULT), twfid.getBytes()));
                recv(socket, serverMessage);
                if (this.mInterruptedTimes > 0) {
                    this.mStartTime = System.currentTimeMillis();
                }
                this.mTurboTimes--;
                this.mInterruptedTimes = 0;
                try {
                    if (0 == 0) {
                        try {
                            if (!handleServerMsg(socket, serverMessage)) {
                                return;
                            }
                            if (TQProtocol.AckMessageType.ACK_NEWSESSION.intValue() == serverMessage.getType()) {
                                continue;
                            } else if (TQProtocol.AckMessageType.ACK_CONNEC.intValue() == serverMessage.getType()) {
                                continue;
                            }
                        } catch (TimeQryException e) {
                            Log.warn(IGeneral.LOG_TAG_TIMEQRY, "Check msg head failed,reconnect.", e);
                            return;
                        }
                    }
                    long j = shouldTurbo() ? QUERY_INTERVAL_TURBO_MODE : this.mQueryInterval;
                    for (int i2 = this.mQueryTimes; i2 > 0; i2--) {
                        synchronized (this.mLock) {
                            this.mLock.wait(j);
                        }
                        if (shouldTurbo()) {
                            break;
                        }
                    }
                    continue;
                } catch (InterruptedException unused) {
                    Log.warn(IGeneral.LOG_TAG_TIMEQRY, "Thread InterruptedException.");
                    return;
                }
            } catch (TimeQryException e2) {
                this.mInterruptedTimes++;
                if (this.mStartTime > 0) {
                    this.mTotalTime += System.currentTimeMillis() - this.mStartTime;
                }
                this.mStartTime = 0L;
                Log.warn(IGeneral.LOG_TAG_TIMEQRY, " data package Exception, reconnect.", e2);
                return;
            } catch (Exception e3) {
                Log.debug(IGeneral.LOG_TAG_TIMEQRY, "fail to send or recv", e3);
                this.mInterruptedTimes++;
                Log.info(IGeneral.LOG_TAG_TIMEQRY, "connect interrupt, timer:" + this.mInterruptedTimes);
                if (this.mStartTime > 0) {
                    this.mTotalTime += System.currentTimeMillis() - this.mStartTime;
                }
                this.mStartTime = 0L;
                Log.warn(IGeneral.LOG_TAG_TIMEQRY, " interrupt time over max time, reconnect.");
                return;
            }
        }
        throw new TimeQryException("Time out exception!");
    }

    private boolean shouldTurbo() {
        boolean z = this.mTurboTimes > 0;
        if (!z) {
            try {
                Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
                String str = "";
                while ("".equals(str) && networkInterfaces.hasMoreElements()) {
                    NetworkInterface nextElement = networkInterfaces.nextElement();
                    if (!"tun0".equals(nextElement.getName()) && !"lo".equals(nextElement.getName()) && nextElement.isUp()) {
                        Enumeration<InetAddress> inetAddresses = nextElement.getInetAddresses();
                        while ("".equals(str) && inetAddresses.hasMoreElements()) {
                            InetAddress nextElement2 = inetAddresses.nextElement();
                            if (!nextElement2.isLoopbackAddress() && !nextElement2.isLinkLocalAddress()) {
                                str = nextElement2.getHostAddress().toString();
                                if (!"".equals(str) && !"".equals(this.mPreIp) && !this.mPreIp.equals(str)) {
                                    Log.debug(IGeneral.LOG_TAG_TIMEQRY, "preIp=" + this.mPreIp + " nowIp=" + str);
                                    z = true;
                                }
                            }
                        }
                    }
                }
                this.mPreIp = str;
            } catch (Exception unused) {
            }
        }
        return z;
    }

    private boolean handShakeWithService(Socket socket) {
        try {
            String str = (String) SettingManager.getInstance().get(SettingManager.TWFID_TWFID);
            Log.info(TAG, "handShakeWithService twfId:" + str);
            send(socket, TQProtocol.fetchHandshakeReqV3(str.getBytes()));
            recv(socket, TQProtocol.fetchServerFixHeaderV3());
            send(socket, TQProtocol.fetchClientAckV3());
            ServerMessage serverMessage = new ServerMessage();
            send(socket, new ClientMessage().pack(4, (int) System.currentTimeMillis(), str.getBytes()));
            recv(socket, serverMessage);
            return handleServerMsg(socket, serverMessage);
        } catch (Exception e) {
            try {
                socket.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            Log.warn(IGeneral.LOG_TAG_TIMEQRY, "failed to exception.", e);
            return false;
        }
    }

    private static void send(Socket socket, byte[] bArr) throws IOException {
        socket.getOutputStream().write(bArr);
        socket.getOutputStream().flush();
    }

    private static int recv(Socket socket, byte[] bArr) throws IOException, TimeQryException {
        if (bArr == null) {
            throw new TimeQryException("Parameter invalid!");
        }
        socket.setSoTimeout(IGeneral.CONN_SERVICE_TIMEOUT);
        int i = 0;
        int length = bArr.length;
        while (i < length) {
            int read = socket.getInputStream().read(bArr, i, length - i);
            if (read == -1) {
                throw new IOException("Socket is closed!");
            }
            i += read;
        }
        return length;
    }

    private static int recv(Socket socket, ServerMessage serverMessage) throws IOException, TimeQryException {
        socket.setSoTimeout(IGeneral.CONN_SERVICE_TIMEOUT);
        byte[] array = serverMessage.toArray();
        int i = 0;
        int i2 = 0;
        while (i2 < 60) {
            int read = socket.getInputStream().read(array, i2, 60 - i2);
            if (read == -1) {
                throw new IOException("Socket is closed!");
            }
            i2 += read;
        }
        if (!serverMessage.checkHead()) {
            throw new TimeQryException("Time query invalid packet!");
        }
        int hBytesToInt = FormatTransfer.hBytesToInt(array, 56, 4);
        if (hBytesToInt != 0) {
            socket.setSoTimeout(IGeneral.CONN_SERVICE_TIMEOUT);
            while (i < hBytesToInt) {
                int read2 = socket.getInputStream().read(array, i + 60, hBytesToInt - i);
                if (read2 == -1) {
                    throw new IOException("Socket is closed!");
                }
                i += read2;
            }
        }
        return hBytesToInt + 60;
    }

    private boolean handleServerMsg(Socket socket, ServerMessage serverMessage) throws TimeQryException {
        if (!serverMessage.checkHead()) {
            throw new TimeQryException("Check msg head failed!");
        }
        TQProtocol.AckMessageType valueOf = TQProtocol.AckMessageType.valueOf(serverMessage.getType());
        Log.info(IGeneral.LOG_TAG_TIMEQRY, "Get ack message type:" + valueOf.name());
        switch (AnonymousClass3.$SwitchMap$com$sangfor$ssl$service$timeqry$TQProtocol$AckMessageType[valueOf.ordinal()]) {
            case 1:
                Log.info(IGeneral.LOG_TAG_TIMEQRY, "connect server success, serv = %s:%d", this.mIpAddr, Integer.valueOf(this.mSslPort));
                break;
            case 2:
            case 3:
                int ackTimeout = serverMessage.getAckTimeout();
                if (ackTimeout > 0) {
                    long currentTimeMillis = System.currentTimeMillis();
                    this.mTimeoutTime.set((ackTimeout * QUERY_INTERVAL_DEFAULT) + currentTimeMillis);
                    Log.info(IGeneral.LOG_TAG_TIMEQRY, "update time to %d, now is %d, ack timeout is %d.", Long.valueOf(this.mTimeoutTime.get()), Long.valueOf(currentTimeMillis), Integer.valueOf(ackTimeout));
                    break;
                } else {
                    Log.warn(IGeneral.LOG_TAG_TIMEQRY, "time not right, time is %d.", Integer.valueOf(ackTimeout));
                    return false;
                }
            case 4:
                Log.info(IGeneral.LOG_TAG_TIMEQRY, "recv a shutdown command.");
                this.mHandler.sendEmptyMessage(7);
                return false;
            case 5:
                Log.info(IGeneral.LOG_TAG_TIMEQRY, " update session.");
                updateSession(serverMessage);
                break;
            case 6:
                Log.debug(IGeneral.LOG_TAG_TIMEQRY, " update time ok.");
                break;
            default:
                Log.warn(IGeneral.LOG_TAG_TIMEQRY, "unkown type = %d.", valueOf);
                break;
        }
        return true;
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    /* renamed from: com.sangfor.ssl.service.timeqry.TimeQryService$3  reason: invalid class name */
    /* loaded from: classes2.dex */
    public static /* synthetic */ class AnonymousClass3 {
        static final /* synthetic */ int[] $SwitchMap$com$sangfor$ssl$l3vpn$service$VpnStatus;
        static final /* synthetic */ int[] $SwitchMap$com$sangfor$ssl$service$timeqry$TQProtocol$AckMessageType;

        static {
            int[] iArr = new int[TQProtocol.AckMessageType.values().length];
            $SwitchMap$com$sangfor$ssl$service$timeqry$TQProtocol$AckMessageType = iArr;
            try {
                iArr[TQProtocol.AckMessageType.ACK_CONNEC.ordinal()] = 1;
            } catch (NoSuchFieldError unused) {
            }
            try {
                $SwitchMap$com$sangfor$ssl$service$timeqry$TQProtocol$AckMessageType[TQProtocol.AckMessageType.ACK_QUERY_EXT.ordinal()] = 2;
            } catch (NoSuchFieldError unused2) {
            }
            try {
                $SwitchMap$com$sangfor$ssl$service$timeqry$TQProtocol$AckMessageType[TQProtocol.AckMessageType.ACK_QUERY.ordinal()] = 3;
            } catch (NoSuchFieldError unused3) {
            }
            try {
                $SwitchMap$com$sangfor$ssl$service$timeqry$TQProtocol$AckMessageType[TQProtocol.AckMessageType.ACK_SHUTDOWN.ordinal()] = 4;
            } catch (NoSuchFieldError unused4) {
            }
            try {
                $SwitchMap$com$sangfor$ssl$service$timeqry$TQProtocol$AckMessageType[TQProtocol.AckMessageType.ACK_NEWSESSION.ordinal()] = 5;
            } catch (NoSuchFieldError unused5) {
            }
            try {
                $SwitchMap$com$sangfor$ssl$service$timeqry$TQProtocol$AckMessageType[TQProtocol.AckMessageType.ACK_UPDATE.ordinal()] = 6;
            } catch (NoSuchFieldError unused6) {
            }
            int[] iArr2 = new int[VpnStatus.values().length];
            $SwitchMap$com$sangfor$ssl$l3vpn$service$VpnStatus = iArr2;
            try {
                iArr2[VpnStatus.VPN_STATUS_CONNECTED.ordinal()] = 1;
            } catch (NoSuchFieldError unused7) {
            }
            try {
                $SwitchMap$com$sangfor$ssl$l3vpn$service$VpnStatus[VpnStatus.VPN_STATUS_RECONNECTING.ordinal()] = 2;
            } catch (NoSuchFieldError unused8) {
            }
        }
    }

    private void updateSession(ServerMessage serverMessage) {
        SettingManager settingManager = SettingManager.getInstance();
        String twfid = GlobalSettingUtils.getTwfid();
        String session = serverMessage.getSession();
        Log.info(IGeneral.LOG_TAG_TIMEQRY, "try update session from %s -> %s", getShortTwfId(twfid), getShortTwfId(session));
        this.mHandler.sendEmptyMessage(4);
        String str = (String) settingManager.getGlobalValue(SettingManager.GLOBAL_HOST_KEY);
        if (!logoutOldSession(str, twfid, session)) {
            Log.warn(IGeneral.LOG_TAG_TIMEQRY, "logout old session failed, try query again");
            setTurboMode(true);
            return;
        }
        if (TextUtils.equals(twfid, (CharSequence) settingManager.get(SettingManager.TWFID_TWFID))) {
            Log.info(IGeneral.LOG_TAG_TIMEQRY, "logout out session finished, commit new session");
            HttpConnect httpConnect = new HttpConnect();
            httpConnect.setCookie(str, IGeneral.COOKIE_TWFID_STRING, session);
            httpConnect.setCookie(str, IGeneral.COOKIE_MBTWFID_STRING, session);
            GlobalSettingUtils.updateTwfid(session);
            SangforAuthForward.getInstance().nSetTwfid(session);
        } else {
            Log.warn(IGeneral.LOG_TAG_TIMEQRY, "session updated by other people during logging out old session");
        }
        this.mHandler.sendEmptyMessage(3);
    }

    private boolean logoutOldSession(String str, String str2, String str3) {
        String str4 = str + URL_SESSION_CHANGE + str2 + "&allocateVip=1";
        SystemConfiguration systemConfiguration = SystemConfiguration.getInstance();
        String authCipher = systemConfiguration.getAuthCipher();
        long gMMode = systemConfiguration.getGMMode();
        HttpConnect httpConnect = new HttpConnect();
        httpConnect.setCookie(str, IGeneral.COOKIE_TWFID_STRING, str3);
        httpConnect.setCookie(str, IGeneral.COOKIE_MBTWFID_STRING, str3);
        try {
            String requestStringWithURL = httpConnect.requestStringWithURL(str4, null, "POST", authCipher, gMMode);
            if (TextUtils.equals(requestStringWithURL, "logout=done")) {
                return true;
            }
            HttpConnect.initializeCookies();
            Log.warn(IGeneral.LOG_TAG_TIMEQRY, "logout old session get unexpected response: " + requestStringWithURL);
            return false;
        } catch (SFException e) {
            Log.error(IGeneral.LOG_TAG_TIMEQRY, "logout old session failed", e);
            return false;
        }
    }

    private void registerRestartTimeQry() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_RESTART_TIMEQRY);
        registerReceiver(this.mReStartTimeQryReceiver, intentFilter);
    }

    private void unRegisterRestartTimeQry() {
        unregisterReceiver(this.mReStartTimeQryReceiver);
    }

    /* JADX INFO: Access modifiers changed from: private */
    /* loaded from: classes2.dex */
    public static class MyHandler extends Handler {
        private WeakReference<TimeQryService> mRef;

        public MyHandler(Looper looper, TimeQryService timeQryService) {
            super(looper);
            this.mRef = new WeakReference<>(timeQryService);
        }

        @Override // android.os.Handler
        public void handleMessage(Message message) {
            super.handleMessage(message);
            TimeQryService timeQryService = this.mRef.get();
            int i = message.what;
            if (i == 1) {
                if (timeQryService != null) {
                    timeQryService.startThread();
                }
            } else if (i == 3) {
                SangforAuthForward.getInstance().setL3vpnLocalStatus(12);
                L3vpnController.getInstance().updateVpnServiceState(LoginState.LOGIN_STATE_ONLINE);
            } else if (i == 4) {
                SangforAuthForward.getInstance().setL3vpnLocalStatus(13);
                L3vpnController.getInstance().updateVpnServiceState(LoginState.LOGIN_STATE_OFFLINE);
            } else if (i == 6) {
                SangforAuthForward.getInstance().setL3vpnLocalStatus(13);
                L3vpnController.getInstance().sendStatusChangedMessage(ReasonCode.STATUS_VPNINFO_ERROR.value());
            } else if (i != 7) {
            } else {
                Log.info(IGeneral.LOG_TAG_TIMEQRY, "receive shutdown command");
                SangforAuthForward.getInstance().setL3vpnLocalStatus(13);
                L3vpnController.getInstance().sendStatusChangedMessage(ReasonCode.STATUS_SERVICE_SHUTDOWN.value());
                L3vpnController.getInstance().respondShutdown();
            }
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    /* loaded from: classes2.dex */
    public class TimeQryTask implements Runnable {
        private volatile boolean mIsInterrupt;

        private TimeQryTask() {
            this.mIsInterrupt = false;
        }

        @Override // java.lang.Runnable
        public void run() {
            runTimeQry();
        }

        public void stop() {
            this.mIsInterrupt = true;
            synchronized (TimeQryService.this.mLock) {
                TimeQryService.this.mLock.notify();
            }
        }

        private void runTimeQry() {
            Log.debug(IGeneral.LOG_TAG_TIMEQRY, " time query thread started.");
            Thread currentThread = Thread.currentThread();
            TimeQryService.this.mTimeoutTime.set(System.currentTimeMillis() + TimeQryService.TIME_QUERY_TIME);
            while (!TimeQryService.this.mIsLogedOut && currentThread == TimeQryService.this.mTimeQryThread && !currentThread.isInterrupted() && !this.mIsInterrupt) {
                Socket connectToServer = TimeQryService.this.connectToServer();
                if (connectToServer != null) {
                    TimeQryService.this.mErrCount = 0L;
                    TimeQryService.this.mTimes = 0L;
                    try {
                        try {
                            TimeQryService.this.mainWork(connectToServer);
                        } finally {
                            TimeQryService.closeSocketQuietly(connectToServer);
                        }
                    } catch (TimeQryException e) {
                        if (this.mIsInterrupt) {
                            Log.warn(IGeneral.LOG_TAG_TIMEQRY, "Thread is interrupt");
                            return;
                        }
                        Log.info(IGeneral.LOG_TAG_TIMEQRY, " time query main work return, time out or logout!", e);
                    }
                } else {
                    Log.info(IGeneral.LOG_TAG_TIMEQRY, "connectToServer failed.");
                    if (this.mIsInterrupt) {
                        Log.warn(IGeneral.LOG_TAG_TIMEQRY, "Thread is interrupt, will exit.");
                        return;
                    }
                    TimeQryService.access$808(TimeQryService.this);
                    try {
                        synchronized (TimeQryService.this.mLock) {
                            TimeQryService.this.mLock.wait(TimeQryService.RECONNECT_INTERVAL_DEFAULT);
                        }
                    } catch (InterruptedException unused) {
                    }
                }
            }
            Log.debug(IGeneral.LOG_TAG_TIMEQRY, " time query thread stopped.");
            TimeQryService.this.stopSelf();
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static void closeSocketQuietly(Socket socket) {
        if (socket != null) {
            try {
                socket.close();
            } catch (Exception unused) {
            }
        }
    }

    private static String getShortTwfId(String str) {
        return str == null ? "null" : str.length() == 0 ? "empty" : str.substring(0, 8);
    }
}
